<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-08-13 16:30:59
-->
<template>
  <div class="content-container">
    <el-row
      type="flex"
      justify="space-between"
      class="header-filter four-border-blueBg"
    >
      <div class="row-left">
        <el-select
          v-model="listParams.status"
          class="item"
          :placeholder="$t('fleet.orderStatus')"
        >
          <el-option
            v-for="item in orderStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <SelectCustomer
          :key="customerKey"
          v-model="listParams.customerId"
          class="item"
          :placeholder="$t('fleet.customerName')"
        />
        <TextInput
          v-model="listParams.vehiclePlate"
          class="item"
          clearable
          :placeholder="$t('fleet.licensePlate')"
        />
        <DateTime
          v-model="listParams.startTime"
          class="item"
          style="min-width: 190px; max-width: 190px"
          clearable
          :default-time="new Date(2025, 1, 1, 0, 0, 0)"
          :label="$t('public.startTime')"
        />
        <el-button type="primary" @click="handleQuery">{{
          $t('public.search')
        }}</el-button>
        <el-button plain @click="handleReset">{{
          $t('public.reset')
        }}</el-button>
      </div>
      <div class="row-right">
        <el-button type="primary" @click="handleCalendar">{{
          $t('public.calendar')
        }}</el-button>
        <el-button type="primary" @click="handleRowCar">{{
          $t('fleet.vehicleScheduleOptimize')
        }}</el-button>
        <el-button type="primary" @click="handleCreate"
          >+ {{ $t('public.create') }}</el-button
        >
        <el-button @click="handleDelete">{{ $t('public.delete') }}</el-button>
      </div>
    </el-row>
    <div class="base-table-container">
      <BaseTable
        ref="refContentTable"
        v-loading="loading"
        :data="tableData"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <TableColumn type="selection" width="43" reserve-selection />
        <TableColumn
          prop="status"
          :label="$t('fleet.orderStatus')"
          s
          :column-width="columnWidthObj.status"
        >
          <template #default="{ row }">
            <span
              class="dot-status"
              :class="
                g_options.getOptionText(
                  g_options.orderStatusOptions,
                  row.status,
                  '--',
                  'class'
                )
              "
              >{{
                g_options.getOptionText(
                  g_options.orderStatusOptions,
                  row.status,
                  '--'
                )
              }}</span
            >
          </template>
        </TableColumn>
        <TableColumn
          prop="allocateStatus"
          :label="$t('fleet.isDispatched')"
          s
          :column-width="columnWidthObj.allocateStatus"
        >
          <template #default="{ row }">
            <span
              class="dot-status"
              :class="
                g_options.getOptionText(
                  g_options.separateCarsOptions,
                  row.allocateStatus,
                  '--',
                  'class'
                )
              "
              >{{
                g_options.getOptionText(
                  g_options.separateCarsOptions,
                  row.allocateStatus,
                  '--'
                )
              }}</span
            >
          </template>
        </TableColumn>
        <TableColumn
          prop="customerName"
          :label="$t('fleet.customerName')"
          :column-width="columnWidthObj.customerName"
        />
        <TableColumn
          prop="departureDate"
          :label="$t('public.departureDate')"
          :column-width="columnWidthObj.departureDate"
        >
          <template #default="{ row }">
            <span>{{ g_dayjs(row.startTime).format('YYYY-MM-DD') }}</span>
          </template>
        </TableColumn>
        <TableColumn
          prop="startTime"
          :label="$t('fleet.departureTime')"
          :column-width="columnWidthObj.startTime"
        >
          <template #default="{ row }">
            <span>{{ g_dayjs(row.startTime).format('HH:mm:ss') }}</span>
          </template>
        </TableColumn>
        <TableColumn
          prop="startCity"
          :label="$t('public.startCity')"
          :column-width="columnWidthObj.startCity"
        >
          <template #default="{ row }">
            <span>{{ row.startCity || '--' }}</span>
          </template>
        </TableColumn>
        <TableColumn
          prop="startAddress"
          :label="$t('public.detailAddress')"
          :column-width="columnWidthObj.startAddress"
        />
        <TableColumn
          prop="region"
          :label="$t('fleet.tripSummary')"
          :column-width="columnWidthObj.region"
        >
          <template #default="{ row }">
            <el-tooltip
              :content="row.note || row.tripAbstract || '--'"
              placement="top"
              effect="dark"
            >
              <span class="twoEllipsis">
                {{ row.note || row.tripAbstract || '--' }}
              </span>
            </el-tooltip>
          </template>
        </TableColumn>
        <TableColumn
          prop="peopleCount"
          :label="$t('fleet.travelerCount')"
          :column-width="columnWidthObj.peopleCount"
        />
        <TableColumn
          prop="days"
          :label="$t('fleet.travelDays')"
          :column-width="columnWidthObj.days"
        />
        <TableColumn
          prop="kilometres"
          :label="$t('fleet.travelDistance')"
          :column-width="columnWidthObj.kilometres"
        />
        <TableColumn
          prop="customerBudget"
          :label="`${$t('fleet.quotePrice')}(${$t('fleet.yuan')})`"
          :column-width="columnWidthObj.customerBudget"
        />
        <TableColumn
          prop="endDate"
          :label="$t('public.endDate')"
          :column-width="columnWidthObj.endDate"
        >
          <template #default="{ row }">
            <span>{{ g_dayjs(row.endTime).format('YYYY-MM-DD') }}</span>
          </template>
        </TableColumn>
        <TableColumn
          prop="endTime"
          :label="$t('public.endTime')"
          :column-width="columnWidthObj.endTime"
        >
          <template #default="{ row }">
            <span>{{ g_dayjs(row.endTime).format('HH:mm:ss') }}</span>
          </template>
        </TableColumn>
        <TableColumn
          prop="endCity"
          :label="$t('public.destinationCity')"
          :column-width="columnWidthObj.endCity"
        >
          <template #default="{ row }">
            <span>{{ row.endCity || '--' }}</span>
          </template>
        </TableColumn>
        <TableColumn
          prop="endAddress"
          :label="$t('public.detailAddress')"
          :column-width="columnWidthObj.endAddress"
        />
        <!-- <TableColumn
          prop="costExpense"
          :label="`${$t('fleet.orderCost')}(${$t('fleet.yuan')})`"
          :column-width="columnWidthObj.costExpense"
        />
        <TableColumn
          prop="orderProfit"
          :label="`${$t('fleet.profit')}(${$t('fleet.yuan')})`"
          :column-width="columnWidthObj.orderProfit"
        /> -->
        <TableColumn
          prop="action"
          fixed="right"
          :label="$t('public.action')"
          max-width="220"
          :column-width="columnWidthObj.action"
        >
          <template #default="{ row }">
            <el-button text @click="handleViewSchedule(row)">
              {{ $t('fleet.schedule') }}
            </el-button>
            <el-button text @click="handleDetailDialog(row, 'view')">
              {{ $t('public.detail') }}
            </el-button>
            <el-button
              text
              :disabled="row.status + '' !== '1'"
              @click="handleQuoteConfirmDialog(row)"
            >
              {{ $t('fleet.quoteConfirm') }}
            </el-button>
            <el-button
              text
              :disabled="
                !(
                  row.status + '' === '1' ||
                  row.status + '' === '2' ||
                  row.status + '' === '3'
                )
              "
              @click="handleEditDialog(row)"
            >
              {{ $t('public.edit') }}
            </el-button>
            <el-button
              text
              :disabled="row.status + '' !== '2'"
              @click="handleDetailDialog(row, 'confirm')"
            >
              {{ $t('fleet.carBookingConfirm') }}
            </el-button>
            <el-button
              text
              :disabled="
                !(
                  row.status + '' === '1' ||
                  row.status + '' === '2' ||
                  row.status + '' === '3'
                )
              "
              @click="handleCancelDialog(row)"
            >
              {{ $t('public.cancel') }}
            </el-button>
            <el-button text @click="handleCostDialog(row)">
              {{ $t('fleet.costManage') }}
            </el-button>
          </template>
        </TableColumn>
      </BaseTable>
      <BasePagination
        v-model:page-size="pageSize"
        v-model:current-page="pageNum"
        :total="total"
        @change="getTableList()"
      />
    </div>
    <!-- 日历 -->
    <Calendar
      v-if="calendarVisible"
      v-model="calendarVisible"
      @update="handleQuery"
    />
    <!-- 排车优化 -->
    <RowCarOptimize
      v-if="rowCarVisible"
      v-model="rowCarVisible"
      @update="handleQuery"
    />
    <!-- 新建/编辑 -->
    <AddOrEditDialog
      v-if="addOrEditVisible"
      :id="rowId"
      v-model="addOrEditVisible"
      :tenant-id="tenantId"
      :type="addOrEditType"
      :row="addOrEditRow"
      @update="handleQuery"
    />
    <!-- 日程 -->
    <Schedule
      v-if="scheduleVisible"
      v-model="scheduleVisible"
      :order-id="rowId"
      type="view"
    />
    <!-- 详情 -->
    <DetailDialog
      v-if="detailVisible"
      :id="rowId"
      v-model="detailVisible"
      :type="detailType"
      @update="handleQuery"
    />
    <!-- 询价确认 -->
    <QuoteConfirm
      v-if="quoteConfirmVisible"
      v-model="quoteConfirmVisible"
      :order-id="rowId"
      @update="handleQuery"
    />
    <!-- 费用管理 -->
    <CostManage
      v-if="costManageVisible"
      v-model="costManageVisible"
      :order-id="rowId"
      @update="handleQuery"
    />
  </div>
</template>

<script setup>
import Calendar from './component/Calendar.vue'
import RowCarOptimize from './component/RowCarOptimize.vue'
import AddOrEditDialog from './component/AddOrEditDialog.vue'
// import Schedule from '@/views/fleet/vehicle/component/Schedule.vue'
import Schedule from './component/Schedule.vue'
import DetailDialog from './component/DetailDialog.vue'
import QuoteConfirm from './component/QuoteConfirm.vue'
import CostManage from './component/CostManage.vue'

const route = useRoute()
const orderStatusOptions = computed(() => {
  return route.name === 'carBooking'
    ? g_options.orderStatusOptions.slice(0, 4)
    : g_options.orderStatusOptions.slice(4)
})
const listParams = ref({
  status: '',
  customerId: '',
  vehiclePlate: '',
  startTime: ''
})
const customerKey = ref(0)
const refContentTable = ref(null)
const loading = ref(false)
const tableData = ref([])
const columnWidthObj = ref({})
const total = ref(0)
const pageSize = ref(10)
const pageNum = ref(1)
const multipleSelection = ref([])
const calendarVisible = ref(false)
const rowCarVisible = ref(false)
const addOrEditVisible = ref(false)
const rowId = ref('')
const tenantId = ref('')
const addOrEditType = ref('add')
const addOrEditRow = ref({})
const scheduleVisible = ref(false)
const detailVisible = ref(false)
const quoteConfirmVisible = ref(false)
const detailType = ref('view')
const costManageVisible = ref(false)

watch(
  () => addOrEditVisible.value,
  nv => {
    if (addOrEditType.value === 'add' && !nv) customerKey.value++
  }
)

watch(
  () => route,
  nv => {
    console.log('watch-route', nv)
    if (nv.query.type === 'add') {
      addOrEditVisible.value = true
      addOrEditRow.value = route.query
    }
  },
  {
    deep: true,
    immediate: true
  }
)

const getTableList = () => {
  loading.value = true
  tableData.value = []
  g_api.fleet
    .apiOrderList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...listParams.value,
      statusList: listParams.value.status
        ? [listParams.value.status]
        : orderStatusOptions.value.map(item => item.value)
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        tableData.value = data.items
        total.value = data.total
        useTableColumnWidth({
          refTable: refContentTable.value
        }).getTableColumnWidth(data => {
          columnWidthObj.value = data
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  getTableList()
})

const handleQuery = () => {
  refContentTable.value.refBaseTable.clearSelection()
  multipleSelection.value = []
  pageNum.value = 1
  getTableList()
}

const handleReset = () => {
  Object.assign(listParams.value, {
    status: '',
    customerId: '',
    vehiclePlate: '',
    startTime: ''
  })
  handleQuery()
}

const handleCalendar = _ => {
  calendarVisible.value = true
}

const handleRowCar = _ => {
  rowCarVisible.value = true
}

const handleCreate = () => {
  addOrEditVisible.value = true
  addOrEditType.value = 'add'
}
const handleDelete = () => {
  if (!multipleSelection.value.length) {
    return ElMessage.warning(g_t('fleet.selectOrder'))
  }
  g_utils
    .deleteConfirm()
    .then(() => {
      loading.value = true
      const list = multipleSelection.value.map(item => ({
        id: item.id,
        status: item.status
      }))
      g_api.fleet
        .apiOrderDelete({
          orderList: list
        })
        .then(res => {
          if (res.code === '200') {
            ElMessage.success(res.message)
            clearTableSelection()
          }
        })
        .finally(() => {
          loading.value = false
        })
    })
    .catch(() => {})
}

const clearTableSelection = () => {
  refContentTable.value.refBaseTable.clearSelection()
  multipleSelection.value = []
  handleQuery()
}

const handleSelectionChange = val => {
  multipleSelection.value = val
}

const handleViewSchedule = row => {
  scheduleVisible.value = true
  rowId.value = row.id
}

const handleDetailDialog = (row, type) => {
  detailVisible.value = true
  detailType.value = type
  rowId.value = row.id
}

const handleQuoteConfirmDialog = row => {
  quoteConfirmVisible.value = true
  rowId.value = row.id
}

const handleCancelDialog = row => {
  ElMessageBox.confirm(
    g_t(`fleet.confirmCancelOrder`, {
      id: row.id
    }),
    g_t('public.tip'),
    {
      confirmButtonText: g_t('public.confirm'),
      cancelButtonText: g_t('public.cancel'),
      type: 'warning'
    }
  )
    .then(() => {
      loading.value = true
      g_api.fleet
        .apiOrderCancel({
          id: row.id,
          customerTripId: row.customerTripId,
          vehicleScheduleId: row.vehicleScheduleId,
          status: 7
        })
        .then(res => {
          if (res.code === '200') {
            ElMessage.success(res.message)
            handleQuery()
          }
        })
        .finally(() => {
          loading.value = false
        })
    })
    .catch(() => {})
}

const handleEditDialog = row => {
  addOrEditVisible.value = true
  addOrEditType.value = 'edit'
  rowId.value = row.id
  tenantId.value = row.tenantId
}

const handleCostDialog = row => {
  costManageVisible.value = true
  rowId.value = row.id
}
</script>

<style lang="scss" scoped></style>
